package com.dave.weixin.common.tulin.util;

import com.dave.weixin.common.tools.RestComponent;
import com.dave.weixin.common.tulin.entity.MessageEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Function;

/**
 * Created by Dave on 2018/7/7
 * Describes
 */
@Component
@PropertySource("classpath:tulin.properties")
@ConfigurationProperties
public class GetMessage {
    private final Logger log = LoggerFactory.getLogger(GetMessage.class);

    @Autowired
    private RestComponent restComponent;
    private String callUrl;

    public String getResponseText(String text) throws IOException {
        MessageEntity me = new MessageEntity();
        me.setInputText(text);
        System.out.println("城市" + me.getCity());

        log.info("请求数据：{}", me.getEntity());
        Map map = restComponent.sendPost(getCallUrl(), me.getEntity(), Map.class);
        return handleMessage(map);


    }

    public String getResponseImage(String url) throws IOException {
        MessageEntity me = new MessageEntity();
        me.setInputImage(url);


        log.info("请求数据：{}", me.getEntity());
        Map map = restComponent.sendPost(getCallUrl(), me.getEntity(), Map.class);
        return handleMessage(map);


    }


    public String getResponseMedia(String url) throws IOException {
        MessageEntity me = new MessageEntity();
        me.setInputMedia(url);

        log.info("请求数据：{}", me.getEntity());
        Map map = restComponent.sendPost(getCallUrl(), me.getEntity(), Map.class);
        return handleMessage(map);


    }

    /**
     * 处理消息
     *
     * @param map
     * @return
     */
    private String handleMessage(Map map) {
        StringBuilder sb = new StringBuilder();
        List<Map<String, Object>> list = (List<Map<String, Object>>) map.get("results");

        if (list != null && list.size() > 0) {

            list.forEach(e -> {
                String valueKey = (String) e.get("resultType");
                Map<String, Object> values = (Map<String, Object>) e.get("values");
                Object o = values.get(valueKey);
                sb.append(o).append("\n");

            });
        }
        return sb.toString();
    }


    public String getCallUrl() {
        return callUrl;
    }

    public void setCallUrl(String callUrl) {
        this.callUrl = callUrl;
    }
}
